package com.woniuxy.woniuticket.realm;

import com.woniuxy.woniuticket.movieinfomodule.dao.ManagementPackageDAO;
import com.woniuxy.woniuticket.movieinfomodule.service.ManagementPackageService;
import com.woniuxy.woniuticket.movieinfomodule.service.UserService;
import com.woniuxy.woniuticket.moviemodule.service.AdminService;
import com.woniuxy.woniuticket.pojo.CinemaLogin;
import com.woniuxy.woniuticket.pojo.ManagementPackage;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;


public class UserRealm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

    @Autowired
    private ManagementPackageService managementPackageService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        CinemaLogin user = (CinemaLogin) principalCollection.getPrimaryPrincipal();
        //查询角色
        List<String> roles = new ArrayList<>();

        ManagementPackage packname = managementPackageService.findById(1);

        roles.add(packname.getPackagename());

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(new HashSet<>(roles));
        return info;
    }

    //登陆验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String) authenticationToken.getPrincipal();
        char[] arr  = (char[]) authenticationToken.getCredentials();
        String pwd = new String(arr);
        CinemaLogin user = new CinemaLogin();
        user.setPassword(pwd);
        user.setAccount(userName);
        CinemaLogin dbUser = adminService.login(userName);
        if(dbUser!=null){
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(dbUser,dbUser.getPassword(),this.getName());
            //用用户的名字加盐
            info.setCredentialsSalt(ByteSource.Util.bytes(dbUser.getAccount()));
            return info;
        }else{
            return null;
        }

    }
}
